<?php

namespace app\admin\controller\member;

use app\admin\model\Order;
use app\common\controller\Backend;
use think\Db;

/**
 * 用户列管理
 *
 * @icon fa fa-circle-o
 */
class Member extends Backend
{

    /**
     * Member模型对象
     * @var \app\admin\model\Member
     */
    protected $model = null;
    protected $order = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Member;

        $this->view->assign("identityList", $this->model->getIdentityList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['partner'])
                ->where($where)
                ->order($sort, $order)
                ->count();
            $list = $this->model
                ->with(['partner'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {
                if(empty($row->agentid)){
                    $row->agentid = '暂无上级';
                }else{
                    $row->agentid = $this->model->where('id',$row->agentid)->find()['nickname'];
                }
            }
            $list = collection($list)->toArray();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        $superior = $this->model->field('nickname')->where('id',$row->agentid)->find();

        $partner = new \app\admin\model\Partner();
        $partnerItem = $partner->where('id',$row->p_id)->find();

        $partnerList = $partner->order('id desc')->select();


        $row->superior = $superior;
        $row->partner = $partnerItem;
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->assignconfig("pid",$row->identity);
        $this->view->assign("row", $row)->assign('partnerList',$partnerList);
        return $this->view->fetch();
    }


    //查看下线
    public function offline()
    {
        $this->assignconfig("ids", $this->request->param("ids"));
        return $this->view->fetch();
    }

    public function offlineList()
    {
        $ids = intval($this->request->param('ids'));
        $this->searchFields = ['nickname', 'mobile', 'id','username'];
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['partner'])
                ->where($where)
                ->where('agentid', $ids)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['partner'])
                ->where($where)
                ->where('agentid', $ids)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }


    //生成合伙人的编号
    public function getMemberSn(){
        if($this->request->isAjax()){
            $id = intval($this->request->param('id'));
            $sn = 'CSM'.date('Y').$id;
            $result = $this->checkSn('CSM',$sn,$id);
            return json(['code'=>1,'data'=>$result]);
        }
    }
    //验证编码的唯一型
    protected function checkSn($prefix,$sn,$id){
        $snList = $this->model->where('membersn',$sn)->select();
        if($snList->isEmpty()){
            return $sn;
        }
        return $prefix.date('Y').$id;
    }

    //查看我的订单
    public function order(){
        $this->assignconfig("ids", $this->request->param("ids"));
        return $this->view->fetch();
    }

    public function orderList(){
        $ids = intval($this->request->param('ids'));
        $memberItem = $this->model->where('id',$ids)->find();
        $this->order = new Order();

        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();




            $total = $this->order
                ->with(['member','discount'])
                ->where($where)
                ->where('order.openid',$memberItem->openid)
                ->order($sort, $order)
                ->count();
            $list = $this->order
                ->with(['member','discount'])
                ->where($where)
                ->where('order.openid',$memberItem->openid)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();


            foreach ($list as $row) {
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    //计算佣金
    public function commission(){
        $this->assignconfig('ids',intval($this->request->param('ids')));
        return $this->view->fetch();
    }

    public function commissionList(){
        $this->model = new Order();
        $this->relationSearch = true;
        $this->searchFields = 'id,ordersn';
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $id = intval($this->request->param('ids'));

            //获取我的下级
            $memberList = $this->infiniteMember($id);




            if(!empty($memberList)){
                $total = 0;
                $orderLists = [];
                foreach ($memberList as $member){
                    $orderLists[] = $this->model
                                    ->with('member')
                                    ->where(['order.openid'=>$member->openid,'order.statis'=> '0','order.status'=> '1'])
                                    ->order($sort, $order)
                                    ->limit($offset, $limit)
                                    ->select()->toArray();

                    $total = $total + $this->model
                                            ->with('member')
                                            ->where(['order.openid'=>$member->openid,'order.statis'=>'0','order.status'=>'1'])
                                            ->order($sort, $order)
                                            ->limit($offset, $limit)
                                            ->count();

                }

                if(!empty($orderLists)){
                    $list = [];
                    foreach ($orderLists as $lists){
                        foreach ($lists as $li){
                            $list[] = $li;
                        }
                    }
                }
            }

            $list = collection($list)->toArray();

            if(!empty($list)){
                $sum = '';
                foreach ($list as $li){
                    $sum += $li['price'];
                }
            }

            $result = array("total" => $total, "rows" => $list,'sum'=>$sum);

            return json($result);
        }
        return $this->view->fetch();
    }

    //佣金计算
    public function commissions(){
        $id = intval($this->request->param('ids'));
        //获取我的下级
        $memberList = $this->infiniteMember($id);
        if(!empty($memberList)){
            //获取下线订单
            $orderLists = [];
            foreach ($memberList as $list){
                $order = new Order();
                $orderLists[] =$order->where(['openid'=>$list->openid,'statis'=>0,'status'=>1])->select();
            }
            if(!empty($orderLists)){
                $orderItem = [];
                foreach ($orderLists as $lists){
                    foreach ($lists as $li){
                        $orderItem[] = $li;
                    }
                }
            }


            return json(['code'=>1,'data'=>$orderItem]);
        }
        return json(['code'=>-1,'msg'=>'暂无下线团队']);
    }

    protected function infiniteMember($id){
        $this->member = new \app\admin\model\Member();
        $memberTeam = $this->member->order('id desc')->select();
        if(empty($memberTeam)){
            return json(['code'=>-1,'msg'=>'暂无下线团队']);
        }

        $memberTeam = $this->sort($memberTeam,$id);
        return $memberTeam;
    }

    protected function sort($data,$pid=0){
        static $arr = array();
        foreach($data as $k=>$v){
            if($v['agentid'] == $pid){
                $arr[] = $v;
                $this->sort($data,$v['id']);
            }
        }
        return $arr;
    }






















}
